package com.unis.service.znzf.impl;

import java.util.*;

import com.unis.common.enums.QqlxEnum;
import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.TemplateUtil;
import com.unis.common.util.TimeUtil;
import com.unis.dto.ResultDto;
import com.unis.mapper.znzf.YhkZtQqMapper;
import com.unis.pojo.znzf.ReqModel;
import com.unis.service.znzf.*;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;
import tk.mybatis.mapper.entity.Example;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.unis.service.impl.BaseServiceImpl;
import com.unis.service.zhxx.TbJdzjfxSfZhService;
import com.unis.mapper.znzf.YhkMxQqMapper;
import com.unis.model.zhxx.TbJdzjfxSfZh;
import com.unis.model.znzf.SfMxQq;
import com.unis.model.znzf.YhkMxQq;
import com.unis.common.exception.app.AppRuntimeException;

/**
 * <pre>
 * @see YhkMxQqService
 * </pre>
 *
 * @author xuk
 * @version 1.0
 * @since 2019-02-12
 */
@Service("yhkMxQqService")
public class YhkMxQqServiceImpl extends BaseServiceImpl implements YhkMxQqService {
    private static final Logger logger = LoggerFactory.getLogger(YhkMxQqServiceImpl.class);
    @Autowired
    private YhkMxQqMapper yhkMxQqMapper;
    @Autowired
    private ZnzfQueueService znzfQueueService;
    @Autowired
    private ZnzfService znzfService;
    @Autowired
    private JltService jltService;
    @Autowired
    private YhkZtQqMapper yhkZtQqMapper;
    @Autowired
    private MxQqGlService mxQqGlService;
    @Autowired
    private TbJdzjfxSfZhService tbJdzjfxSfZhService;

    /**
     * @see YhkMxQqService#insert(YhkMxQq yhkMxQq)
     */
    @Override
    public int insert(YhkMxQq yhkMxQq) throws Exception {
        if (yhkMxQq != null) {
            yhkMxQq.setPk(TemplateUtil.genUUID());

            UserInfo user = this.getUserInfo();
            yhkMxQq.setLrdwdm(user.getJgdm());
            yhkMxQq.setLrdwmc(user.getJgmc());
            yhkMxQq.setLrrxm(user.getXm());
            yhkMxQq.setLrrjh(user.getJh());
            //menu.setPk(getPk("seqName","jgdm","A"));

            return yhkMxQqMapper.insertSelective(yhkMxQq);
        } else {
            logger.error("YhkMxQqServiceImpl.insert时yhkMxQq数据为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.insert时yhkMxQq数据为空。");
        }
    }

    @Override
    public int insertYhkMx(ReqModel reqModel) throws Exception {
        int resultNumber = 0;
        Map bean = null;
        if (reqModel != null && reqModel.getBean() != null && !reqModel.getBean().isEmpty() && reqModel.getBean().size() > 0) {
            List<Map> list;
            UserInfo user = this.getUserInfo();
            Date nowDate = this.getDbDate();
            for (Map<String, String> map : reqModel.getBean()) {
                list = new ArrayList<>();
                if (map == null || map.isEmpty() || map.size() < 1) {
                    continue;
                }
                bean = new HashMap();

                bean.put("pk", TemplateUtil.genUUID());
                bean.put("ztpk", TemplateUtil.genUUID());
                bean.put("lrdwdm", user.getJgdm());
                bean.put("lrdwmc", user.getJgmc());
                bean.put("lrrxm", user.getXm());
                bean.put("lrrjh", user.getJh());
//                bean.put("jjdpk", reqModel.getJjdPk());
                String jjdPk = map.get("jjdPk");
                bean.put("jjdpk", jjdPk);
                bean.put("reason", reqModel.getSy());
                bean.put("subjecttype", Short.parseShort(map.get("zhlb")));
                bean.put("bankcode", map.get("zhjgdm"));
                bean.put("bankname", map.get("zhjgmc"));
                bean.put("accountname", map.get("zhxm"));

                String zh = StringUtils.isNotBlank(map.get("zh")) ? map.get("zh") : "";
                bean.put("cardnumber", zh);

                bean.put("inquirymode", map.get("cxnr"));
                bean.put("inquiryperiodstart", StringUtils.isNotBlank(map.get("startDate")) ? TimeUtil.strToDate(map.get("startDate"), "yyyy-MM-dd") : DateUtils.addDays(nowDate, -1));
                bean.put("inquiryperiodend", StringUtils.isNotBlank(map.get("endDate")) ? TimeUtil.strToDate(map.get("endDate"), "yyyy-MM-dd") : nowDate);
                bean.put("zhlx", map.get("zhlx"));

                //增加转账时间
                bean.put("zzsj", StringUtils.isNotBlank(map.get("zzsj")) ? TimeUtil.strToDate(map.get("zzsj"), null) : null);
                String mongoPk = "";
                Example example = new Example(YhkMxQq.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("yxx", 1);
                criteria.andEqualTo("jjdpk", jjdPk);
                criteria.andEqualTo("lrdwdm", user.getJgdm());
                criteria.andEqualTo("bankcode", bean.get("zhjgdm"));
                criteria.andEqualTo("bankname", bean.get("zhjgmc"));
                List<YhkMxQq> qqList = this.queryListByExample(example);
                if (qqList != null && !qqList.isEmpty()) {
                    mongoPk = qqList.get(0).getFlws();
                } else {
                    mongoPk = znzfService.insertMongo("yhk", "cx", bean);
                }
                bean.put("flws", mongoPk);

                bean.put("nlevel", 1);
                bean.put("sertype", new Short("1"));
                bean.put("parentpk", reqModel.getParentpk());
                bean.put("parentzh", reqModel.getParentzh());
                bean.put("iszcygzs", reqModel.getIszcygzs());
                list.add(bean);
                List<Map> queueList = new ArrayList();
                jltService.checkJltAndInsert(bean);
                bean.put("kssj", bean.get("inquiryperiodstart"));
                bean.put("jssj", bean.get("inquiryperiodend"));
                bean.put("glpk", TemplateUtil.genUUID());
                queueList.add(bean);
                //明细请求
                resultNumber = yhkMxQqMapper.insertBatch(list);
                mxQqGlService.insertBatch(queueList);
                znzfQueueService.insertBatchMx(queueList, QqlxEnum.yhkQqlxMxcx.getKey(), (short) 1);

                //主体请求
                resultNumber = yhkZtQqMapper.insertBatchZt(list);
                znzfQueueService.insertBatchZt(list, QqlxEnum.yhkQqlxZtcx.getKey(), (short) 1);
                TbJdzjfxSfZh tbJdzjfxSfZh = tbJdzjfxSfZhService.queryTbJdzjfxSfZhByPrimaryKey(jjdPk);
                tbJdzjfxSfZh.setCj("1");
                tbJdzjfxSfZh.setFxbs((short) 2);
                tbJdzjfxSfZh.setFxsj(new Date());
                tbJdzjfxSfZhService.updateByPrimaryKey(tbJdzjfxSfZh);
            }
        }
        return resultNumber;
    }

    /**
     * 复制map对象
     *
     * @param paramsMap 被拷贝对象
     * @param resultMap 拷贝后的对象
     * @explain 将paramsMap中的键值对全部拷贝到resultMap中；
     * paramsMap中的内容不会影响到resultMap（深拷贝）
     */
    private static void mapCopy(Map paramsMap, Map resultMap) {
        if (resultMap == null) {
            resultMap = new HashMap();
        }
        if (paramsMap == null) {
            return;
        }

        Iterator it = paramsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            resultMap.put(key, paramsMap.get(key) != null ? paramsMap.get(key) : "");

        }
    }

    /**
     * @see YhkMxQqService#delete(String pk)
     */
    @Override
    public int delete(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("YhkMxQqServiceImpl.delete时pk为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.delete时pk为空。");
        } else {
            return yhkMxQqMapper.deleteByPrimaryKey(pk);
        }
    }

    /**
     * @see YhkMxQqService#updateByPrimaryKey(YhkMxQq yhkMxQq)
     */
    @Override
    public int updateByPrimaryKey(YhkMxQq yhkMxQq) throws Exception {
        if (yhkMxQq != null) {
            if (StringUtils.isBlank(yhkMxQq.getPk())) {
                logger.error("YhkMxQqServiceImpl.updateByPrimaryKey时yhkMxQq.Pk为空。");
                throw new AppRuntimeException("YhkMxQqServiceImpl.updateByPrimaryKey时yhkMxQq.Pk为空。");
            }
            return yhkMxQqMapper.updateByPrimaryKeySelective(yhkMxQq);
        } else {
            logger.error("YhkMxQqServiceImpl.updateByPrimaryKey时yhkMxQq数据为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.updateByPrimaryKey时yhkMxQq数据为空。");
        }
    }

    @Override
    public int updateLevelByJlt(String jjdpk, String cardnumber, int nlevel, int newNlevel, int thisNlevel) throws Exception {
        return yhkMxQqMapper.updateNlevel(jjdpk, cardnumber, nlevel, newNlevel, thisNlevel);
    }

    /**
     * @see YhkMxQqService#queryYhkMxQqByPrimaryKey(String pk)
     */
    @Override
    public YhkMxQq queryYhkMxQqByPrimaryKey(String pk) throws Exception {
        if (StringUtils.isBlank(pk)) {
            logger.error("YhkMxQqServiceImpl.queryYhkMxQqByPrimaryKey时pk为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.queryYhkMxQqByPrimaryKey时pk为空。");
        } else {
            return yhkMxQqMapper.selectByPrimaryKey(pk);
        }
    }


    /**
     * @see YhkMxQqService#queryAsObject(YhkMxQq yhkMxQq)
     */
    @Override
    public YhkMxQq queryAsObject(YhkMxQq yhkMxQq) throws Exception {
        if (yhkMxQq != null) {
            return yhkMxQqMapper.selectOne(yhkMxQq);
        } else {
            logger.error("YhkMxQqServiceImpl.queryAsObject时yhkMxQq数据为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.queryAsObject时yhkMxQq数据为空。");
        }
    }

    /**
     * @see YhkMxQqService#queryCountByExample(Example example)
     */
    @Override
    public int queryCountByExample(Example example) throws Exception {
        if (example != null) {
            return yhkMxQqMapper.selectCountByExample(example);
        } else {
            logger.error("YhkMxQqServiceImpl.queryCountByExample时example数据为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.queryCountByExample时example数据为空。");
        }
    }

    /**
     * @see YhkMxQqService#queryListByExample(Example example)
     */
    @Override
    public List<YhkMxQq> queryListByExample(Example example) throws Exception {
        if (example != null) {
            return yhkMxQqMapper.selectByExample(example);
        } else {
            logger.error("YhkMxQqServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see YhkMxQqService#queryPageInfoByExample(Example example, int pageNum, int pageSize)
     */
    @Override
    public PageInfo queryPageInfoByExample(Example example, int pageNum, int pageSize) throws Exception {
        if (example != null) {
            PageHelper.startPage(pageNum, pageSize);
            return new PageInfo(yhkMxQqMapper.selectByExample(example));
        } else {
            logger.error("YhkMxQqServiceImpl.queryListByExample时example数据为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.queryListByExample时example数据为空。");
        }
    }

    /**
     * @see YhkMxQqService#queryListByPage(Map parmMap, int pageNum, int pageSize)
     */
    @Override
    public ResultDto queryListByPage(Map parmMap, int pageNum, int pageSize) throws Exception {
        if (parmMap != null) {
            Example example = new Example(YhkMxQq.class);
            //example.setOrderByClause("rksj DESC,pk asc");设置排序
            Example.Criteria criteria = example.createCriteria();
            //criteria设置
            // = --> andEqualTo(field,value)
            // like --> andLike(field,likeValue)；likeValue 包含‘%’
            // is null --> andIsNull(field)
            // is not null --> andIsNotNull(field)
            // <> --> andNotEqualTo(field)
            // > --> andGreaterThan(field,value)
            // >= --> andGreaterThanOrEqualTo(field,value)
            // < --> andLessThan(field,value)
            // <= --> andLessThanOrEqualTo(field,value)
            // in --> andIn(field,Iterable value)
            // not in --> andNotIn(field,Iterable value)
            // between --> andBetween(field,beginValue,endValue)
            // not like --> andNotLike(field,likeValue)；likeValue 包含‘%’

            // or --> 上述方法的and 都有与之对应的or方法 eg: orEqualTo(field,value)

            //criteria.andEqualTo("yxx",1);设置yxx=1
            /**
             *此方法请根据需要修改下方条件
             */
            //此查询仅针对单表查询，若需要多表查询，尽量使用配置Mapper.xml 和Mapper.java的方式
            //生成条件中均为 and field = value
            //生成代码中，若表结构中有_等字符，生成字段可能会与实体类不同，请注意修改

            boolean flag = false;
            if (parmMap.get("pk") != null && StringUtils.isNotBlank(parmMap.get("pk").toString())) {
                criteria.andEqualTo("pk", parmMap.get("pk").toString().trim());
                flag = true;
            }
            if (parmMap.get("jjdpk") != null && StringUtils.isNotBlank(parmMap.get("jjdpk").toString())) {
                criteria.andEqualTo("jjdpk", parmMap.get("jjdpk").toString().trim());
                flag = true;
            }
            if (parmMap.get("applicationid") != null && StringUtils.isNotBlank(parmMap.get("applicationid").toString())) {
                criteria.andEqualTo("applicationid", parmMap.get("applicationid").toString().trim());
                flag = true;
            }
            if (parmMap.get("subjecttype") != null && StringUtils.isNotBlank(parmMap.get("subjecttype").toString())) {
                criteria.andEqualTo("subjecttype", parmMap.get("subjecttype").toString().trim());
                flag = true;
            }
            if (parmMap.get("bankcode") != null && StringUtils.isNotBlank(parmMap.get("bankcode").toString())) {
                criteria.andEqualTo("bankcode", parmMap.get("bankcode").toString().trim());
                flag = true;
            }
            if (parmMap.get("bankname") != null && StringUtils.isNotBlank(parmMap.get("bankname").toString())) {
                criteria.andEqualTo("bankname", parmMap.get("bankname").toString().trim());
                flag = true;
            }
            if (parmMap.get("accountname") != null && StringUtils.isNotBlank(parmMap.get("accountname").toString())) {
                criteria.andEqualTo("accountname", parmMap.get("accountname").toString().trim());
                flag = true;
            }
            if (parmMap.get("cardnumber") != null && StringUtils.isNotBlank(parmMap.get("cardnumber").toString())) {
                criteria.andEqualTo("cardnumber", parmMap.get("cardnumber").toString().trim());
                flag = true;
            }
            if (parmMap.get("inquirymode") != null && StringUtils.isNotBlank(parmMap.get("inquirymode").toString())) {
                criteria.andEqualTo("inquirymode", parmMap.get("inquirymode").toString().trim());
                flag = true;
            }
            if (parmMap.get("inquiryperiodstart") != null && StringUtils.isNotBlank(parmMap.get("inquiryperiodstart").toString())) {
                criteria.andEqualTo("inquiryperiodstart", parmMap.get("inquiryperiodstart").toString().trim());
                flag = true;
            }
            if (parmMap.get("inquiryperiodend") != null && StringUtils.isNotBlank(parmMap.get("inquiryperiodend").toString())) {
                criteria.andEqualTo("inquiryperiodend", parmMap.get("inquiryperiodend").toString().trim());
                flag = true;
            }
            if (parmMap.get("reason") != null && StringUtils.isNotBlank(parmMap.get("reason").toString())) {
                criteria.andEqualTo("reason", parmMap.get("reason").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrdwdm") != null && StringUtils.isNotBlank(parmMap.get("lrdwdm").toString())) {
                criteria.andEqualTo("lrdwdm", parmMap.get("lrdwdm").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrdwmc") != null && StringUtils.isNotBlank(parmMap.get("lrdwmc").toString())) {
                criteria.andEqualTo("lrdwmc", parmMap.get("lrdwmc").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrrxm") != null && StringUtils.isNotBlank(parmMap.get("lrrxm").toString())) {
                criteria.andEqualTo("lrrxm", parmMap.get("lrrxm").toString().trim());
                flag = true;
            }
            if (parmMap.get("lrrjh") != null && StringUtils.isNotBlank(parmMap.get("lrrjh").toString())) {
                criteria.andEqualTo("lrrjh", parmMap.get("lrrjh").toString().trim());
                flag = true;
            }
            if (parmMap.get("rksj") != null && StringUtils.isNotBlank(parmMap.get("rksj").toString())) {
                criteria.andEqualTo("rksj", parmMap.get("rksj").toString().trim());
                flag = true;
            }
            if (parmMap.get("yxx") != null && StringUtils.isNotBlank(parmMap.get("yxx").toString())) {
                criteria.andEqualTo("yxx", parmMap.get("yxx").toString().trim());
                flag = true;
            }
            if (parmMap.get("reqflag") != null && StringUtils.isNotBlank(parmMap.get("reqflag").toString())) {
                criteria.andEqualTo("reqflag", parmMap.get("reqflag").toString().trim());
                flag = true;
            }
            if (parmMap.get("reqdate") != null && StringUtils.isNotBlank(parmMap.get("reqdate").toString())) {
                criteria.andEqualTo("reqdate", parmMap.get("reqdate").toString().trim());
                flag = true;
            }
            if (parmMap.get("reqcount") != null && StringUtils.isNotBlank(parmMap.get("reqcount").toString())) {
                criteria.andEqualTo("reqcount", parmMap.get("reqcount").toString().trim());
                flag = true;
            }
            if (parmMap.get("resflag") != null && StringUtils.isNotBlank(parmMap.get("resflag").toString())) {
                criteria.andEqualTo("resflag", parmMap.get("resflag").toString().trim());
                flag = true;
            }
            if (parmMap.get("resdate") != null && StringUtils.isNotBlank(parmMap.get("resdate").toString())) {
                criteria.andEqualTo("resdate", parmMap.get("resdate").toString().trim());
                flag = true;
            }
            if (parmMap.get("resultcode") != null && StringUtils.isNotBlank(parmMap.get("resultcode").toString())) {
                criteria.andEqualTo("resultcode", parmMap.get("resultcode").toString().trim());
                flag = true;
            }
            if (parmMap.get("feedbackremark") != null && StringUtils.isNotBlank(parmMap.get("feedbackremark").toString())) {
                criteria.andEqualTo("feedbackremark", parmMap.get("feedbackremark").toString().trim());
                flag = true;
            }
            //一个条件都没有的时候给一个默认条件
            if (!flag) {

            }
            PageInfo pageInfo = this.queryPageInfoByExample(example, pageNum, pageSize);
            ResultDto result = new ResultDto();
            result.setRows(pageInfo.getList());
            result.setPage(pageInfo.getPageNum());
            //result.setTotal(pageInfo.getPages());
            result.setTotal((int) pageInfo.getTotal());
            return result;
        } else {
            logger.error("YhkMxQqServiceImpl.queryListByPage时parmMap数据为空。");
            throw new AppRuntimeException("YhkMxQqServiceImpl.queryListByPage时parmMap数据为空。");
        }
    }
}
